package org.dant.ant.extension.utils;

import java.lang.reflect.*;
import java.util.*;

import org.dant.ant.extension.tasks.internal.RemoteCommand;

public final class ParameterUtil {
    private static String[] excludeList = {"getRuntimeConfigurableWrapper", "getProject", "getResultsList", "getTransmit", "getowningtarget", "getlocation",
                                           "getowningtestcase", "gettestsuitename", "gettestcasename"};
    
    private ParameterUtil() {
    }

    private static boolean inExcludeList(String key) {
        if (key == null) {
            return true;
        }
        for (int i = 0; i < excludeList.length; i++) {
            if (key.equalsIgnoreCase(excludeList[i])) {
                return true;
            }
        }
        return false;
    }
  
    private static String getFiledName(String methodName) {
        return methodName.substring(3).toLowerCase();
    }

    public static Map resolve(Object obj, boolean thisClz) throws Exception {
        Class clz = obj.getClass();
        Map parameters = new HashMap();
        Method[] methods = clz.getMethods();
        for (int i = 0; i < methods.length; i++) {
            String name = methods[i].getName();

            if (!"java.lang.Object".equals(methods[i].getDeclaringClass().getName())
                && name.startsWith("get")
                && !"void".equals(methods[i].getReturnType().getName())) {
                if (inExcludeList(name)) {
                    continue;
                }
                if (thisClz) {
                    if (clz.getName().equals(methods[i].getDeclaringClass().getName())) {
                        parameters.put(getFiledName(name), methods[i].invoke(obj, null));
                    }
                } else {
                    parameters.put(getFiledName(name), methods[i].invoke(obj, null));
                }
            }
        }
        return parameters;
    }

    public static int  getInt(RemoteCommand rcmd, String key) {
        Object obj = rcmd.getParameters().get(key);
        if (obj != null && obj.getClass() == int.class) {
            return new Integer(obj.toString()).intValue();
        }
        return 0;
    }
}
